package com.webdemo9.contrller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webdemo9.bean.UsersBean;
import com.webdemo9.dao.UsersDao;
import com.webdemo9.dao.impl.UsersDaoFactory;

/**
 * 显示用户列表
 * @author lovemanai
 *
 */
public class ListUsers extends HttpServlet {

	private UsersDao usersDao = UsersDaoFactory.getUsersDao();
	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int PAGE_SIZE = Integer.parseInt(this.getServletContext().getInitParameter("pagesize").toString());
		int pageNo = 1;
		boolean headState = false;
		boolean trailState = false;
		String startPage = request.getParameter("pageno");
		String errorcode = request.getParameter("errorcode");
		if(startPage != null && !startPage.trim().equals("")) {
			try {
				pageNo = Integer.parseInt(startPage);
			} catch(NumberFormatException e) {
				pageNo = 1;
			}
		}
		int totalRecords = usersDao.getTotalRecords();
		int totalPage = (totalRecords % PAGE_SIZE == 0) ? (totalRecords / PAGE_SIZE) : (totalRecords / PAGE_SIZE + 1); 
		if(pageNo <= 1 ) {
			pageNo = 1;
			headState = true;
		}
		if(pageNo >= totalPage) {
			trailState = true;
		}
		int startPos = (pageNo - 1) * PAGE_SIZE;
		List<UsersBean> userList = usersDao.search(startPos, PAGE_SIZE);
		request.setAttribute("userlist", userList);
		request.setAttribute("headstate", headState);
		request.setAttribute("trailstate", trailState);
		request.setAttribute("pageno", pageNo);
		request.setAttribute("totalpage", totalPage);
		request.setAttribute("errorcode", errorcode);
		RequestDispatcher rd = request.getRequestDispatcher("list.jsp");
		rd.forward(request, response);
	}

}
